package com.pur.zsms.weixin.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.lianchuang.service.CoreService;
import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.common.util.CipherUtil;
import com.pur.zsms.common.util.SignUtil;
import com.pur.zsms.matermanage.mater.vo.MaterVo;
import com.pur.zsms.ordercustommanage.po.OrderDistributorPo;
import com.pur.zsms.ordercustommanage.po.OrderSupplierPo;
import com.pur.zsms.ordercustommanage.service.ISelectFoodService;
import com.pur.zsms.ordercustommanage.vo.OrderDistributorVo;
import com.pur.zsms.pmsnmanage.role.po.RolePo;
import com.pur.zsms.pmsnmanage.role.service.IRoleService;
import com.pur.zsms.pmsnmanage.role.vo.RoleVo;
import com.pur.zsms.pmsnmanage.user.po.UserPo;
import com.pur.zsms.pmsnmanage.user.service.IUserService;
import com.pur.zsms.pmsnmanage.user.vo.LdAddressVo;
import com.pur.zsms.pmsnmanage.user.vo.UserVo;
import com.pur.zsms.service.IDistributorService;
import com.pur.zsms.shopmanage.po.ShopPo;
import com.pur.zsms.shopmanage.po.ShopUserPo;
import com.pur.zsms.shopmanage.service.IShopService;
import com.pur.zsms.supplier.po.SupplierUserPo;
import com.pur.zsms.supplier.service.ISupplierService;
import com.pur.zsms.supplier.vo.SupplierUserVo;
import com.pur.zsms.systemsetting.datadictionary.service.IDataDictionaryService;
import com.pur.zsms.systemsetting.datadictionary.vo.CodeVo;
import com.pur.zsms.weixin.bean.Access_token;
import com.pur.zsms.weixin.service.IWeixinService;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;

@Controller
@RequestMapping(value = "/weixintest")
public class WeixinControllor {
	private String token = "weixinCourse";
	private String encodingAESKey = "smYKvlLNrw3BQRb4laoY0oz3Umgoz1tYFHfjXywG5ee";
	private String corpId = "ZSMSL_2013";

	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(WeixinControllor.class);

	protected int page = 1;

	protected int pageSize = 15;

	PaginationSupport pageList;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	@Resource(name = "selectFoodService")
	private ISelectFoodService selectFoodService;
	@Resource(name = "distributorService")
	private IDistributorService distributorService;

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "weixinService")
	private IWeixinService weixinService;

	@Resource(name = "coreService")
	private CoreService coreService;

	@Resource(name = "roleService")
	private IRoleService roleService;

	@Resource(name = "dictionaryService")
	private IDataDictionaryService dataDictionaryService;

	@Resource(name = "supplierService")
	private ISupplierService supplierService;

	@Resource(name = "shopService")
	private IShopService shopService;

	@RequestMapping(value = "/weixintest.do", method = { RequestMethod.GET })
	public ModelAndView weixintest(String code, String state, HttpSession session) throws IOException {
		// 拼接api要求的httpsurl链接
		String openId = getOpenId(code);
		java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
		map.put("openId", openId);
		// 从数据库取openId 的用户 如果有则直接进入业务界面 没有则进入 用户关联界面
		try {
			List<UserPo> list = userService.getUsePoListByOpenId(openId);

			if (list != null && list.size() > 0) {
				UserPo userInfo = new UserPo();
				userInfo = list.get(0);
				map.put("userName", userInfo.getUserName());
				/*
				 * Map map = new HashMap(); map.put("openId", openId);
				 * session.setAttribute("user", userInfo);
				 * session.setAttribute("mobile", "open"); return new
				 * ModelAndView("redirect:/jsp/main.jsp", map);
				 */
				// 手机版
				session.setAttribute("user", userInfo);
				session.setAttribute("mobile", "open");

				if (state.equals("123")) {
					/*
					 * List<RolePo> rolePolist2 =
					 * roleService.getRolePoByRoleNameUserId(userInfo, "收银"); if
					 * (rolePolist2 != null && rolePolist2.size() > 0) { return
					 * new ModelAndView(
					 * "redirect:/jsp-mobile/cashier/mainMobileForCashier.jsp",
					 * map); } List<RolePo> rolePolist =
					 * roleService.getRolePoByRoleNameUserId(userInfo, "供货商");
					 * if (rolePolist != null && rolePolist.size() > 0) { return
					 * new
					 * ModelAndView("redirect:/jsp-mobile/mainMobileForSupplier.jsp"
					 * , map); } else { return new
					 * ModelAndView("redirect:/jsp-mobile/mainMobile.jsp", map);
					 * }
					 */
					return new ModelAndView("redirect:/jsp/weixin/message/successWeixin.jsp", map);
				} else if (state.equals("1001")) {// 客户订单
					// 校验 是否为供应商
					SupplierUserVo c = new SupplierUserVo();
					c.setUserId(list.get(0).getUserId());
					List<SupplierUserPo> listPo = supplierService.getSupplierUserPo(c);
					if (listPo == null || listPo.size() == 0) {
						map.put("msg", "您没有供货商权限！请联系管理员添加权限！");
						return new ModelAndView("/jsp-mobile/deal/error", map);
					} else {
						return new ModelAndView("redirect:/jsp-mobile/ordermanage/customOrderForSup_mobile.jsp", map);
					}

				} else if (state.equals("1002")) {// 分销商订单
					// 校验 是否为供应商
					SupplierUserVo c = new SupplierUserVo();
					c.setUserId(list.get(0).getUserId());
					List<SupplierUserPo> listPo = supplierService.getSupplierUserPo(c);
					if (listPo == null || listPo.size() == 0) {
						map.put("msg", "您没有供货商权限！请联系管理员添加权限！");
						return new ModelAndView("/jsp-mobile/deal/error", map);
					} else {
						return new ModelAndView("redirect:/jsp-mobile/ordermanage/distributorOrderIndexForSup_mobile.jsp", map);
					}

				} else if (state.equals("1003")) {// 供货商订单
					// 校验 是否为供应商
					SupplierUserVo c = new SupplierUserVo();
					c.setUserId(list.get(0).getUserId());
					List<SupplierUserPo> listPo = supplierService.getSupplierUserPo(c);
					if (listPo == null || listPo.size() == 0) {
						map.put("msg", "您没有供货商权限！请联系管理员添加权限！");
						return new ModelAndView("/jsp-mobile/deal/error", map);
					} else {
						return new ModelAndView("redirect:/jsp-mobile/ordermanage/distributorOrderIndex_mobile.jsp", map);
					}

				} else if (state.equals("1004")) {// 采购
					// 校验 是否为店长
					List<ShopUserPo> listShopUser = shopService.getShopUserPoByUserId(userInfo.getUserId());
					if (listShopUser == null || listShopUser.size() == 0) {
						map.put("msg", "您没有店员权限！请联系管理员添加权限！");
						return new ModelAndView("/jsp-mobile/deal/error", map);
					} else {
						return new ModelAndView("redirect:/jsp-mobile/select/selectMater_mobile.jsp", map);
					}
				} else if (state.equals("1005")) {// 订单审核
					// 校验 是否为店长
					List<ShopUserPo> listShopUser = shopService.getShopUserPoByUserId(userInfo.getUserId());
					if (listShopUser == null || listShopUser.size() == 0) {
						map.put("msg", "您没有店员权限！请联系管理员添加权限！");
						return new ModelAndView("/jsp-mobile/deal/error", map);
					} else {
						return new ModelAndView("redirect:/jsp-mobile/ordermanage/customOrder_mobile.jsp", map);
					}
				} else if (state.equals("1006")) {// 供货商订单
					// 校验 是否为店长
					List<ShopUserPo> listShopUser = shopService.getShopUserPoByUserId(userInfo.getUserId());
					if (listShopUser == null || listShopUser.size() == 0) {
						map.put("msg", "您没有店员权限！请联系管理员添加权限！");
						return new ModelAndView("/jsp-mobile/deal/error", map);
					} else {
						return new ModelAndView("redirect:/jsp-mobile/ordermanage/customOrderMaterIndex_mobile.jsp", map);
					}
				} else if (state.equals("1234")) {
					// 解除绑定
					weixinService.associationOpenIdOut(userInfo);
					return new ModelAndView("redirect:/jsp/weixin/message/successWeixin.jsp", map);

				}
				session.removeAttribute("user");
			} else if (!state.equals("123")) {
				return new ModelAndView("/weixin/message/NoHaveUser", map);
			}
		} catch (GenericException e) {
			session.removeAttribute("user");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("/weixinlogin", map);
	}

	@RequestMapping(value = "/weixinJumpForOut.do", method = { RequestMethod.GET })
	public ModelAndView weixinJumpForOut(String code, String state, HttpSession session) throws IOException {
		// 拼接api要求的httpsurl链接
		String openId = getOpenId(code);
		java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
		// 从数据库取openId 的用户 如果有则直接进入业务界面 没有则进入 用户关联界面

		map.put("openId", openId);
		return new ModelAndView("/weixinloginOut", map);

	}

	public static String getOpenId(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx64bdfb1d6682c965&secret=84b1db883fbb66d23fd959ba418d2e38&code="
				+ code + "&grant_type=authorization_code";
		String openId = "";
		try {
			URL getUrl = new URL(url);
			HttpURLConnection http = (HttpURLConnection) getUrl.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);

			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] b = new byte[size];
			is.read(b);

			String message = new String(b, "UTF-8");

			JSONObject json = JSONObject.fromObject(message);
			openId = json.getString("openid");

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return openId;
	}

	@RequestMapping(value = "/associationOpenId.do", method = { RequestMethod.POST })
	@ResponseBody
	public String associationOpenId(UserVo c, HttpSession session) {
		JSONObject json = new JSONObject();
		try {
			UserPo userPo = weixinService.associationOpenId(c);
			if (userPo.getUserId() != 0) {
				session.setAttribute("user", userPo);
				session.setAttribute("mobile", "open");
				json.put("success", true);
			} else {
				json.put("msg", weixinService.getMsg());
				json.put("success", false);
			}

		} catch (Exception e) {
			e.printStackTrace();
			json.put("success", false);
		}
		return json.toString();
	}

	// 解除绑定
	@RequestMapping(value = "/associationOut.do", method = { RequestMethod.POST })
	public String associationOut(String openId) throws IOException {
		// 拼接api要求的httpsurl链接
		// 从数据库取openId 的用户 如果有则直接进入业务界面 没有则进入 用户关联界面
		JSONObject json = new JSONObject();
		try {
			List<UserPo> list = userService.getUsePoListByOpenId(openId);
			if (list != null && list.size() > 0) {
				UserPo userInfo = new UserPo();
				userInfo = list.get(0);
				weixinService.associationOpenIdOut(userInfo);
				Map map = new HashMap();
			} else {
				Map map = new HashMap();
			}
			json.put("success", true);
		} catch (GenericException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json.toString();
	}

	@RequestMapping(value = "/weixinOrder.do", method = { RequestMethod.GET })
	public ModelAndView weixinOrder(String code, String state, HttpSession session) throws IOException {
		// 拼接api要求的httpsurl链接
		String openId = getOpenId(code);
		java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
		map.put("openId", openId);
		// 从数据库取openId 的用户 如果有则直接进入业务界面 没有则进入 用户关联界面
		try {
			List<UserPo> list = userService.getUsePoListByOpenId(openId);

			if (list != null && list.size() > 0) {
				UserPo userInfo = new UserPo();
				userInfo = list.get(0);
				map.put("userName", userInfo.getUserName());
				/*
				 * Map map = new HashMap(); map.put("openId", openId);
				 * session.setAttribute("user", userInfo);
				 * session.setAttribute("mobile", "open"); return new
				 * ModelAndView("redirect:/jsp/main.jsp", map);
				 */
				// 手机版
				session.setAttribute("user", userInfo);
				session.setAttribute("mobile", "open");

				long supId = supplierService.getSupIdByUserId(userInfo.getUserId());
				// 取得订单状态
				OrderDistributorVo tOrderDistributorVo = new OrderDistributorVo();
				tOrderDistributorVo.setOrdSupId((int) supId);
				// tOrderDistributorVo.setOrdDistributorId(ordDistributorId);
				tOrderDistributorVo.setOrdId(Integer.valueOf(state));
				OrderDistributorPo tOrderDistributorPo = distributorService.getOrderDistributorPo(tOrderDistributorVo);
				map.put("OrderDistributorPo", tOrderDistributorPo);

				return new ModelAndView("/jsp-mobile/ordermanage/distributorDetailedIndexForSup_mobile", map);
			}
		} catch (GenericException e) {
			session.removeAttribute("user");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("/weixinlogin", map);
	}

	@RequestMapping(value = "/weixinOrderForSupToCust.do", method = { RequestMethod.GET })
	public ModelAndView weixinOrderForSupToCust(String code, String state, HttpSession session) throws IOException {
		// 拼接api要求的httpsurl链接
		String openId = getOpenId(code);
		java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
		map.put("openId", openId);
		// 从数据库取openId 的用户 如果有则直接进入业务界面 没有则进入 用户关联界面
		try {
			List<UserPo> list = userService.getUsePoListByOpenId(openId);

			if (list != null && list.size() > 0) {
				UserPo userInfo = new UserPo();
				userInfo = list.get(0);
				map.put("userName", userInfo.getUserName());
				/*
				 * Map map = new HashMap(); map.put("openId", openId);
				 * session.setAttribute("user", userInfo);
				 * session.setAttribute("mobile", "open"); return new
				 * ModelAndView("redirect:/jsp/main.jsp", map);
				 */
				// 手机版
				session.setAttribute("user", userInfo);
				session.setAttribute("mobile", "open");

				long supId = supplierService.getSupIdByUserId(userInfo.getUserId());
				// 取得订单状态
				OrderSupplierPo tOrderSupplierPo = selectFoodService.getOrderSupplierPoByOrdIdAndSupId(state, String.valueOf(supId)).get(0);
				map.put("ordState", tOrderSupplierPo.getOrdState());
				map.put("tOrderSupplierPo", tOrderSupplierPo);

				map.put("ordId", state);
				map.put("supId", supId);
				ShopPo shopPo = shopService.getShopPoByOrdId(Long.valueOf(state));
				map.put("shopPo", shopPo);
				map.put("shopName", shopPo.getShopName());

				return new ModelAndView("/jsp-mobile/ordermanage/customDetailedMaterIndexForSup_mobile", map);
			}
		} catch (GenericException e) {
			session.removeAttribute("user");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView("/weixinlogin", map);
	}

}
